package CmdHandle;

import javafx.concurrent.Task;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import utils.CommandDefault;
import xmlParse.XmlParser;

import java.io.*;
import java.nio.charset.StandardCharsets;

import static utils.CommonComponent.getPlatformBASeparator;
import static utils.CommonComponent.getPlatformSeparator;

/**
 * 更新记录：修改 app 为调试版本的
 */
public class MakeLogPackage extends Task<Integer> {
    private TextField source;
    private TextField target;
    private String[] mCmd;
    private Text textLog;
    //进度条的进度值
    private int indicateValue=0;
    public MakeLogPackage(TextField source, TextField target, String[] mCmd, Text textLog) {
        this.source = source;
        this.target = target;
        this.mCmd = mCmd;
        this.textLog = textLog;
    }

    @Override
    protected void updateMessage(String message) {
        super.updateMessage(message);
        textLog.setText(message);
    }

    @Override
    protected Integer call() throws Exception {
        String content = null;
        super.updateProgress(CommandDefault.MIN_PROGRESS,CommandDefault.MAX_PROGRESS);
        //反编译
        content = handleCommandForMakeLogApk(mCmd[0]);
        super.updateMessage(content);
        if(indicateValue<20){
            indicateValue=20;
            updateProgress(0);
        }
        String decodeTargetPath = target.getText().substring(0, target.getText().lastIndexOf("."));
        //插入一条语句
        //解析xml
        File file = new File(decodeTargetPath + getPlatformSeparator() + "AndroidManifest.xml");
        System.out.println("解析xml路径:" + file.getAbsolutePath());
        XmlParser xmlParser = new XmlParser(file);
        //调试版本 apk
        xmlParser.injectDebuggable();
        String relativePath = xmlParser.parseManifest();
        System.out.println("获取到启动界面activity路径:" + relativePath);
        injectSdkLog(relativePath);
        if(indicateValue<40){
            indicateValue=40;
            updateProgress(0);
        }
        //反打包
        content += handleCommandForMakeLogApk(mCmd[1]);
        super.updateMessage(content);
        if(indicateValue<70){
            indicateValue=70;
            updateProgress(0);
        }
        //签名
        content += handleCommandForMakeLogApk(mCmd[2]);
        super.updateMessage(content);
        if(indicateValue<100){
            indicateValue=100;
            updateProgress(0);
        }
        return null;
    }
    //注入日志
    private void injectSdkLog(String relativePath) {
        try {
            //fileReader targetPath+"/smali/"+relativePath+".smali"
            String targetPath = target.getText().substring(0, target.getText().lastIndexOf("."));
            File targetFile = new File(targetPath + getPlatformBASeparator("smali") + relativePath + ".smali");
            //获取文件名
            String targetFileName = targetFile.getName();
            FileReader fileReader = new FileReader(targetFile);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            //需要生成的文件
            File generateFile = new File(targetPath + getPlatformBASeparator("smali") + targetFileName);
            FileWriter fileWriter = new FileWriter(generateFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            String line;
            StringBuilder content = new StringBuilder();
            //准备工作完成
            updateProgress(10);
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(".method protected onCreate(Landroid/os/Bundle;)V")) {
                    for (int i = 0; i < 10; i++) {
                        content.append(line + "\n");
                        line = bufferedReader.readLine();
                    }
                    content.append(line+"\n");
                    content.append("invoke-static {},Lcom/Qsu;->Log()V\n");
                } else {
                    content.append(line + "\n");
                }
            }
            bufferedReader.close();
            bufferedWriter.write(content.toString());
            bufferedWriter.flush();
            bufferedWriter.close();
            if (targetFile.delete()) {
                generateFile.renameTo(targetFile);
            }
            updateProgress(10);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    private String handleCommandForMakeLogApk(String cmd) {
        System.out.println("start command:"+cmd);
        Runtime run = Runtime.getRuntime();
        String content = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader;
        Process p = null;
        updateProgress(5);
        System.out.println("Preparatory work completed");
        try {
            p = run.exec(cmd);
            inputStreamReader = new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8);
            bufferedReader = new BufferedReader(inputStreamReader);
            content = getContentLog(bufferedReader);
            p.waitFor();
            updateProgress(10);
            bufferedReader.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return content;
    }

    private String getContentLog(BufferedReader bufferedReader) throws IOException {
        String line;
        String content = "";
        while ((line = bufferedReader.readLine()) != null) {
            content += line + "\n";
        }
        updateProgress(10);
        System.out.println(content);
        return content;

    }
    private void updateProgress(int value){
        indicateValue+=value;
        System.out.println("进度值为:"+indicateValue);
        super.updateProgress(CommandDefault.MIN_PROGRESS+indicateValue,CommandDefault.MAX_PROGRESS);
    }
}
